{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys,copy,os,inspect\n",
    "if hasattr(sys.modules[__name__], '__file__'):\n",
    "    _file_name = __file__\n",
    "else:\n",
    "    _file_name = inspect.getfile(inspect.currentframe())\n",
    "CURRENT_FILE_PATH = os.path.dirname(_file_name)\n",
    "sys.path.append(os.getcwd()+\"/../neuronVis\")\n",
    "import pandas as pd\n",
    "import Scene\n",
    "import BrainRegion as BR \n",
    "import IONData \n",
    "iondata = IONData.IONData()\n",
    "\n",
    "def loadClusterCSV(filename,cluster=None):\n",
    "    neurons = pd.read_csv(filename)\n",
    "    neuronsArray= neurons.to_numpy()\n",
    "    neuronScene=[]\n",
    "    for neuron in neuronsArray:\n",
    "        # print(str(neuron[2])[0])\n",
    "        neurondict={}\n",
    "        neurondict['cluster'] = neuron[1]\n",
    "        neurondict['sampleid'] = str(neuron[2])[0:6]\n",
    "        neurondict['name']=str(neuron[2])[6:]+'.swc'\n",
    "        if cluster ==neuron[1] or cluster ==None:\n",
    "            neuronScene.append(neurondict)\n",
    "    return neuronScene\n",
    "neuronScene = loadClusterCSV(\"../resource/cluster_eachNeuron/cluster_eachNeuron_TH.csv\")\n",
    "br = BR.BrainRegion()\n",
    "br.praseJson()\n",
    "\n",
    "neurons = Scene.scene2List(\"../resource/TH.nv\")\n",
    "target_regions = ['SSp','SSs','VISC','GU','VISp','VISam','VISpm','VISa','AUDp','AUDv','AUDd','TEa','MOp','MOs','ORBl','ORBvl','ORBm','PL','AIv','AIp','AId','ACAd','ACAv','RSPagl','RSPd']\n",
    "source_regions_sort_index = ['VPM','VPL','VPMpc','VPLpc','LGd','MG','VAL','AM','SMT','MD','LP','PO','LD','VM','RE','CM']\n",
    "regionNeurons={}\n",
    "\n",
    "for regions in source_regions_sort_index:\n",
    "    regionNeurons[regions]=[]\n",
    "for neuron in neurons:\n",
    "    property = iondata.getNeuronPropertyByID(neuron['sampleid'], neuron['name'])\n",
    "    if property['somaregion'] not in source_regions_sort_index:\n",
    "        continue\n",
    "    else:\n",
    "        regionNeurons[property['somaregion']].append(neuron)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'module' object is not callable",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32md:\\project\\python\\neuron-vis\\figures\\thSample.ipynb 单元格 2\u001b[0m in \u001b[0;36m<cell line: 6>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      <a href='vscode-notebook-cell:/d%3A/project/python/neuron-vis/figures/thSample.ipynb#X20sZmlsZQ%3D%3D?line=3'>4</a>\u001b[0m \u001b[39mimport\u001b[39;00m \u001b[39mnumpy\u001b[39;00m \u001b[39mas\u001b[39;00m \u001b[39mnp\u001b[39;00m\n\u001b[0;32m      <a href='vscode-notebook-cell:/d%3A/project/python/neuron-vis/figures/thSample.ipynb#X20sZmlsZQ%3D%3D?line=4'>5</a>\u001b[0m data \u001b[39m=\u001b[39m IONData\u001b[39m.\u001b[39mIONData()\n\u001b[1;32m----> <a href='vscode-notebook-cell:/d%3A/project/python/neuron-vis/figures/thSample.ipynb#X20sZmlsZQ%3D%3D?line=5'>6</a>\u001b[0m fig \u001b[39m=\u001b[39m plt\u001b[39m.\u001b[39;49mfigure(figsize\u001b[39m=\u001b[39;49m(\u001b[39m10\u001b[39;49m,\u001b[39m10\u001b[39;49m))\n\u001b[0;32m      <a href='vscode-notebook-cell:/d%3A/project/python/neuron-vis/figures/thSample.ipynb#X20sZmlsZQ%3D%3D?line=6'>7</a>\u001b[0m ax \u001b[39m=\u001b[39m fig\u001b[39m.\u001b[39madd_subplot(\u001b[39m111\u001b[39m)\n\u001b[0;32m      <a href='vscode-notebook-cell:/d%3A/project/python/neuron-vis/figures/thSample.ipynb#X20sZmlsZQ%3D%3D?line=7'>8</a>\u001b[0m color \u001b[39m=\u001b[39m np\u001b[39m.\u001b[39marray((\u001b[39m'\u001b[39m\u001b[39m66\u001b[39m\u001b[39m'\u001b[39m,\u001b[39m'\u001b[39m\u001b[39m133\u001b[39m\u001b[39m'\u001b[39m,\u001b[39m'\u001b[39m\u001b[39m244\u001b[39m\u001b[39m'\u001b[39m))\u001b[39m.\u001b[39mastype(\u001b[39mfloat\u001b[39m)\u001b[39m/\u001b[39m\u001b[39m255\u001b[39m\n",
      "\u001b[1;31mTypeError\u001b[0m: 'module' object is not callable"
     ]
    }
   ],
   "source": [
    "import matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib as plt\n",
    "import numpy as np\n",
    "data = IONData.IONData()\n",
    "fig = plt.figure(figsize=(10,10))\n",
    "ax = fig.add_subplot(111)\n",
    "color = np.array(('66','133','244')).astype(float)/255\n",
    "for edge in data.getNeuronTreeByID('210661','162.swc').getDendrite():\n",
    "    X = []\n",
    "    for k in edge.data[::1]:\n",
    "        X.append(k.xyz)\n",
    "    X = np.array(X)\n",
    "    ax.plot(-X[:,2],-X[:,1],linewidth=4,color=color)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import Visual as nv\n",
    "# neuronvis = nv.neuronVis()\n",
    "# neuronvis.render.setBackgroundColor([1,1,1])\n",
    "# neuronvis.render.setView('vontral')\n",
    "# for region in source_regions_sort_index:\n",
    "#     for neuron in regionNeurons[region]:\n",
    "#         neuronT = iondata.getNeuronTreeByID(neuron['sampleid'], neuron['name'])\n",
    "#         neuronvis.addNeuronTree(neuronT,'200313-083.swc',somaColor=[1,0,0],axonColor=[1,0,0],dendriteColor=[1,0,0])\n",
    "#         neuronvis.render.savepng(\"../resource/thsample/th2isosample/\"+region+neuron['sampleid']+ neuron['name']+'.png')\n",
    "#         neuronvis.clear()\n",
    "# neuronvis.render.closeWindow()\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import matplotlib\n",
    "matplotlib.use('module://matplotlib_inline.backend_inline')\n",
    "%matplotlib inline\n",
    "import FlatNeuron\n",
    "\n",
    "grid,dv0,dv1,dv2,flatenPara = FlatNeuron.getStreamLine()\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### test sample"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# fig,ax = FlatNeuron.plt.subplots(figsize=(11,7))\n",
    "    \n",
    "neurontree = iondata.getNeuronTreeByID('192106','001.swc')\n",
    "\n",
    "FlatNeuron.flatneuron(neurontree,grid,dv0,dv1,dv2,flatenPara)\n",
    "# FlatNeuron.plt.savefig('../resource/thsample/th2isosample/test.png', format='png', dpi=300)\n",
    "FlatNeuron.plt.show()\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## all neuron"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os.path\n",
    "\n",
    "\n",
    "\n",
    "for region in source_regions_sort_index:\n",
    "    for neuron in regionNeurons[region]:\n",
    "        # if not os.path.isfile(\"../resource/thsample/th2isosample/\"+region+neuron['sampleid']+ neuron['name']+'flat.png'):\n",
    "            neuronT = iondata.getNeuronTreeByID(neuron['sampleid'], neuron['name'])\n",
    "            FlatNeuron.flatneuron(neuronT,grid,dv0,dv1,dv2,True)\n",
    "            FlatNeuron.plt.savefig(\"../resource/thsample/th2isosample/\"+region+neuron['sampleid']+ neuron['name']+'flat.png', format='png', dpi=300)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cluster"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "thNeuronDF = pd.DataFrame(neuronScene)\n",
    "\n",
    "import Visual as nv\n",
    "neuronvis = nv.neuronVis()\n",
    "neuronvis.render.setBackgroundColor([1,1,1])\n",
    "neuronvis.render.setView('vontral')\n",
    "\n",
    "for clusterid in range(1,12):\n",
    "    clusterdf = thNeuronDF[thNeuronDF['cluster']==clusterid]\n",
    "\n",
    "    row_indexs = []\n",
    "    for index, row in clusterdf.iterrows():\n",
    "        neuronT = iondata.getNeuronTreeByID(row['sampleid'], row['name'])\n",
    "        neuronvis.addNeuronTree(neuronT,'200313-083.swc',somaColor=[1,0,0],axonColor=[1,0,0],dendriteColor=[1,0,0],mirrorToRight=True)\n",
    "        # neuronvis.render.savepng(\"../resource/thsample/thclustersample/\"+str(clusterid)+'_'+row['sampleid']+ row['name']+'.png')\n",
    "    neuronvis.render.savepng(\"../resource/thsample/thclustersample/\"+'cluster'+str(clusterid)+'.png')\n",
    "    neuronvis.clear()\n",
    "neuronvis.render.closeWindow()\n",
    "\n",
    "# single neuron\n",
    "neuronvis = nv.neuronVis()\n",
    "neuronvis.render.setBackgroundColor([1,1,1])\n",
    "neuronvis.render.setView('vontral')\n",
    "\n",
    "for clusterid in range(1,12):\n",
    "    clusterdf = thNeuronDF[thNeuronDF['cluster']==clusterid]\n",
    "\n",
    "    row_indexs = []\n",
    "    for index, row in clusterdf.iterrows():\n",
    "        neuronT = iondata.getNeuronTreeByID(row['sampleid'], row['name'])\n",
    "        neuronvis.addNeuronTree(neuronT,'200313-083.swc',somaColor=[1,0,0],axonColor=[1,0,0],dendriteColor=[1,0,0],mirrorToRight=True)\n",
    "        neuronvis.render.savepng(\"../resource/thsample/thclustersample/\"+str(clusterid)+'_'+row['sampleid']+ row['name']+'.png')\n",
    "    # neuronvis.render.savepng(\"../resource/thsample/thclustersample/\"+'cluster'+str(clusterid)+'.png')\n",
    "        neuronvis.clear()\n",
    "neuronvis.render.closeWindow()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### RT neurons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rtNeurons=[]\n",
    "\n",
    "for neuron in neuronScene:\n",
    "    property = iondata.getNeuronPropertyByID(neuron['sampleid'], neuron['name'])\n",
    "    proj = property['projectregion']\n",
    "    if 'RT' in proj:\n",
    "        rtNeurons.append(neuron)\n",
    "# print(len(rtNeurons))\n",
    "rtregionNeurons={}\n",
    "for regions in source_regions_sort_index:\n",
    "    rtregionNeurons[regions]=[]\n",
    "for neuron in rtNeurons:\n",
    "    property = iondata.getNeuronPropertyByID(neuron['sampleid'], neuron['name'])\n",
    "    if property['somaregion'] not in source_regions_sort_index:\n",
    "        continue\n",
    "    else:\n",
    "        rtregionNeurons[property['somaregion']].append(neuron)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import Visual as nv\n",
    "neuronvis = nv.neuronVis()\n",
    "neuronvis.render.setBackgroundColor([1,1,1])\n",
    "neuronvis.render.setLookAt(eye=(-4550,-8000,4000),center=(0,0,0),up=(-1,0,0))\n",
    "neuronvis.render.setLookAt(eye=(-2550,-4000,2000),center=(-1500,-2000,0),up=(-1,0,0))\n",
    "\n",
    "for region,neurons in rtregionNeurons.items():\n",
    "\tneuronvis.addRegion('RT',color=[0.5,0.5,0])\n",
    "\tneuronvis.addRegion(region,color=[0.5,0.0,0])\n",
    "\tfor neuron in neurons:\n",
    "\n",
    "\t\tneuronT = iondata.getNeuronTreeByID(neuron['sampleid'], neuron['name'])\n",
    "\t\tneuronvis.addNeuronTree(neuronT,'200313-083.swc',somaColor=[1,0,0],axonColor=[1,0,0],dendriteColor=[0,0,1])\n",
    "\t\tneuronvis.render.savepng(\"../resource/thsample/th2rtsample/\"+region+neuron['sampleid']+ neuron['name']+'.png')\n",
    "\t\tneuronvis.clear(regions=False)\n",
    "\tneuronvis.clear(regions=True)\n",
    "\t\n",
    "neuronvis.render.closeWindow()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import Visual as nv\n",
    "neuronvis = nv.neuronVis()\n",
    "neuronvis.render.setBackgroundColor([1,1,1])\n",
    "neuronvis.addRegion('RT',color=[0.5,0.5,0])\n",
    "neuronvis.addRegion('PO',color=[0.5,0.5,0])\n",
    "neuronvis.render.setLookAt(eye=(-2550,-4000,2000),center=(-1500,-2000,0),up=(-1,0,0))\n",
    "neuronT = iondata.getNeuronTreeByID('210661', '197.swc')\n",
    "neuronvis.addNeuronTree(neuronT,'200313-083.swc',somaColor=[1,0,0],axonColor=[1,0,0],dendriteColor=[0,0,1])\n",
    "neuronvis.render.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(len(neuronScene))\n",
    "for neuron in neuronScene:\n",
    "    # print(neuron)\n",
    "    if not os.path.isfile('../resource/thsample/flatmap/'+neuron['sampleid']+'-'+neuron['name']+'.png'):\n",
    "\n",
    "        neuronT = iondata.getNeuronTreeByID(neuron['sampleid'],neuron['name'])\n",
    "        FlatNeuron.flatneuron(neuronT,grid,dv0,dv1,dv2,flatenPara)\n",
    "        FlatNeuron.plt.savefig('../resource/thsample/flatmap/'+neuron['sampleid']+'-'+neuron['name']+'.png', format='png', dpi=300)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.8.3 ('neuronVis')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "e1da01a652087c3f485a2a8b69806c32fa3b3acf94bcdc0c1ef74e2af5cc794e"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
